<?php
/**
 * 请求校验中间件
 */

namespace App\Http\Middleware;

use Closure;
use App\Http\Controllers\Controller;
use App\Exceptions\ErrorResponse;

use Illuminate\Support\Facades\Validator;

class RequestValidate
{
    /**
     * 请求
     * @param $request
     * @param Closure $next
     * @param mixed ...$guards
     * @return mixed
     * @throws \Exception
     */
    public function handle($request, Closure $next, ...$guards)
    {
        list($controller, $action) = explode('@', $request->route()->getActionName());
        $validateClass = str_replace('Controller', 'Validate', $controller);
        // 验证规则方法不存在，默认不校验
        if (class_exists($validateClass) && is_callable([$validateClass, $action])) {
            $validateRule = call_user_func([$validateClass, $action]);
            $validator = Validator::make($request->all(), $validateRule);
            if ($validator->fails()) {
                ErrorResponse::illegalParam($validator->errors()->first());
            }

            Controller::$params = $validator->getData();
        }

        return $next($request);
    }
}
